package com.web.controller;

import com.alibaba.fastjson.JSON;
import com.web.entity.ResponseResult;
import com.web.entity.Student;
import com.web.service.StudentService;
import com.web.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addStudent")
public class AddStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");

        // 获取请求参数
        String name = req.getParameter("name");
        String ageStr = req.getParameter("age");
        String gender = req.getParameter("gender");
        String address = req.getParameter("address");
        String cellphone = req.getParameter("cellphone");
        // 获取性别参数

        // 参数验证
        if (name == null || name.isEmpty() || ageStr == null || ageStr.isEmpty() || gender == null || gender.isEmpty()) {
            resp.getWriter().write(JSON.toJSONString(new ResponseResult(400, "姓名、年龄和性别不能为空", null)));
            return;
        }

        try {
            int age = Integer.parseInt(ageStr);
            Student student = new Student(); // 创建 Student 对象
            student.setName(name); // 设置姓名
            student.setAge(age); // 设置年龄
            student.setGender(gender); // 设置性别
            student.setAddress(address);
            student.setCellphone(cellphone);

            StudentService studentService = new StudentServiceImpl();
            boolean success = studentService.addStudent(student); // 传递 Student 对象

            if (success) {
                resp.getWriter().write(JSON.toJSONString(new ResponseResult(200, "添加成功", null)));
            } else {
                resp.getWriter().write(JSON.toJSONString(new ResponseResult(500, "添加失败", null)));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(JSON.toJSONString(new ResponseResult(400, "年龄格式不正确", null)));
        }
    }
}
